<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2021/8/17
 * Time: 20:24
 */

namespace app\service;



use OSS\Core\OssException;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\Exception;
use think\facade\App;
use think\facade\Config;
use think\facade\Db;
use think\facade\Env;

class AliyunService
{
   public static function getimgsuffix($name) {
        $info = getimagesize($name);
        $suffix = false;
        if($mime = $info['mime']){
            $suffix = explode('/',$mime)[1];
        }
        return $suffix;
    }

    public static function uploadToQiniu($url,$fileName){
        $accessKey = Env::get('QINIU.QINIUAccessKey');
        $secretKey = Env::get('QINIU.QINIUAccessKeySecret');
        $bucket = Env::get('QINIU.QINIUBucket');
        $auth = new Auth($accessKey, $secretKey);
        $config = new \Qiniu\Config();
        $config->useHTTPS = true; // 接口是否使用 HTTPS 协议
        $bucketManager = new BucketManager($auth, $config);
        $callbackurl = "http://cdn.133926.com/upload_verify_callback.php";
        $callbackbody = '{"key":"$(key)","hash":"$(etag)","w":"$(imageInfo.width)","h":"$(imageInfo.height)"}';
//---------------------------------------- demo1 ----------------------------------------
// 指定抓取的文件保存到七牛云空间中的名称
        $key =$fileName;
      #  list($ret, $err) = $bucketManager->asynchFetch($url, $bucket, null, $key, null, null, $callbackurl, $callbackbody);
        list($ret, $err) = $bucketManager->fetch($url, $bucket,  $key);
        if ($err !== null) {
            var_dump($err);
            echo '转存储被限制，3秒后从新发起'.$url;
            sleep(3);
           self::uploadToQiniu($url,$fileName);
        }
        return 'http://hk.133926.com/'.$key;
    }

    public static function uploadByUrl($url,$store_id,$store_type=''){
        if(strpos($url,'http')===false&&strpos($url,'https')===false){
            $url = 'http:'.$url;
        }
        if(strpos($url,'http:https')!==false){
            $url = str_replace('http:','',$url);
        }
        $bucket = Env::get('ALIYUN.Bucket');
        $accessKeyId = Env::get('ALIYUN.AccessKey');
        $accessKeySecret = Env::get('ALIYUN.AccessKeySecret');
         $endpoint = Env::get('ALIYUN.Endpoint');
        $myEndpoint = Env::get('ALIYUN.MyEndpoint');

     /*   $bucket ='yajiadatest1111';
        $accessKeyId = 'LTAI5tB6iQ9MpH5XC2fsDbV3';
        $accessKeySecret = 'ZybqdMZv3mQTReWGOJ4M5va5MEW4LT';
        $endpoint = 'oss-accelerate.aliyuncs.com';
        $myEndpoint = 'http://yajiadatest1111.oss-accelerate.aliyuncs.com';*/
        $fix = self::getimgsuffix($url);
        $fix = '.'.$fix;
        $fileName = md5($url).$fix;
        $fileData = array(
            'store_id'=>113,
            'store_type'=>'',
            'group'=>-1,
            'upload_mode'=>2,
            'image_name'=>$fileName,
            'add_time'=>date('Y-m-d H:i:s'),
            'mch_id'=>225,
            'alternative_text'=>'',
            'recycle'=>0,
        );
        $filePath = $store_id . '/' . $store_type.'/'.$fileName;
        $dir = $store_id . '/' . $store_type . '/' . $fileName;
        Db::name('lkt_files_record')->data($fileData)->insert();
        #转存储到七牛
        echo '正在转存储'.$url.PHP_EOL;
        $url = self::uploadToQiniu($url,$fileName);
        echo '七牛转存储成功'.$url.PHP_EOL;
        $data = file_get_contents($url);
        $object = App::getRootPath().'/upload/'.$fileName;
        file_put_contents($object,$data);
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket,$filePath, $object);
             unlink($object);
        } catch(OssException $e) {
                echo '阿里云上传错误'.$e->getMessage();die;
        }
        echo '上传文件'.$myEndpoint.'/'.$filePath.PHP_EOL;
        return  $myEndpoint.'/'.$filePath;
    }

   public static  function download($url, $filename)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, $url);

        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $fp = @fopen($filename, "a");
        fwrite($fp, $return_content);

        return $return_content;
    }
}